/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Interfaces.ApparentModalI;
import Interfaces.Pinakas;
import Model.Album;
import Model.Song;
import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JTable;
import src.ApparentModalC;
import src.General;

/**
 * Πίνακας των άλμπουμ (καλλιτεχνών ή μουσικών συγκροτημάτων κατά περίσταση)
 *
 */
public class AlbumTableJFrame extends javax.swing.JFrame implements Pinakas<Album>, ApparentModalI {

    private Album selectedAlbumClone;
    private RadioStationJFrame caller;
    private JFrame next;
    private final boolean isArtistAlbum;
    private final String queryStr;
    private final EntityManager RadioStationPUEntityManager;
    private final Query albumQuery;
    private final List<Album> albumList;

    /**
     * Creates new form ArtistsAlbumTableJFrame
     */
    public AlbumTableJFrame() {
        throw new UnsupportedOperationException();

    }

    public AlbumTableJFrame(RadioStationJFrame caller, boolean isArtistAlbum) {
        initComponents();
        this.isArtistAlbum = isArtistAlbum;
        if (this.isArtistAlbum) {
            this.queryStr = "SELECT a FROM Album a WHERE a.artistId is not null";
        } else {
            this.queryStr = "SELECT a FROM Album a WHERE a.musicGroupId is not null";
        }

        RadioStationPUEntityManager = General.getEntityManager();
        albumQuery = RadioStationPUEntityManager.createQuery(queryStr);
        albumList = org.jdesktop.observablecollections.ObservableCollections.observableList(albumQuery.getResultList());
        if (this.isArtistAlbum) {
            this.bindArtistAlbumTableToList();
        } else {
            this.bindGroupAlbumTableToList();
            this.setTitle("Πίνακας άλμπουμ συγκροτημάτων");
        }

        this.caller = caller;
        try {
            General.setWindowImage(this);
        } catch (Exception ex) {
        }
        // SimpleDateFormat στο πεδίο ημ/νία κυκλοφορίας
        General.assignSimpleDateFormatToJTableColumn(5, jTable1);
        this.jTable1.getRowSorter().toggleSortOrder(0);
        this.enableDeleteUpdateIf();
        this.disableDeleteUpdateIf();
    }

    public boolean getIsArtistAlbum() {
        return this.isArtistAlbum;
    }

    private void bindArtistAlbumTableToList() {
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, albumList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumTitle}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${typeId}"));
        columnBinding.setColumnName("Τύπος");
        columnBinding.setColumnClass(Model.Albumtype.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${companyId}"));
        columnBinding.setColumnName("Εταιρεία");
        columnBinding.setColumnClass(Model.Musicproductioncompany.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${diskNumber}"));
        columnBinding.setColumnName("Αριθμός");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artistId}"));
        columnBinding.setColumnName("Καλλιτέχνης");
        columnBinding.setColumnClass(Model.Artist.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${releaseDate}"));
        columnBinding.setColumnName("Ημ/νία κυκλοφορίας");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        jTableBinding.bind();
    }

    private void bindGroupAlbumTableToList() {
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, albumList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${albumTitle}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${typeId}"));
        columnBinding.setColumnName("Τύπος");
        columnBinding.setColumnClass(Model.Albumtype.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${companyId}"));
        columnBinding.setColumnName("Εταιρεία");
        columnBinding.setColumnClass(Model.Musicproductioncompany.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${diskNumber}"));
        columnBinding.setColumnName("Αριθμός");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicGroupId}"));
        columnBinding.setColumnName("Συγκρότημα");
        columnBinding.setColumnClass(Model.Musicgroup.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${releaseDate}"));
        columnBinding.setColumnName("Ημ/νία κυκλοφορίας");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        jTableBinding.bind();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        DeletejButton2 = new javax.swing.JButton();
        EditjButton3 = new javax.swing.JButton();
        ExitjButton5 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        AddjButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Πίνακας άλμπουμ καλλιτεχνών");
        setMinimumSize(new java.awt.Dimension(823, 430));

        DeletejButton2.setText("Διαγραφή");
        DeletejButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeletejButton2ActionPerformed(evt);
            }
        });

        EditjButton3.setText("Μεταβολή");
        EditjButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditjButton3ActionPerformed(evt);
            }
        });

        ExitjButton5.setText("Έξοδος");
        ExitjButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitjButton5ActionPerformed(evt);
            }
        });

        jLabel1.setText("Διαχείρiση άλμπουμ");

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTable1);

        AddjButton1.setText("Εισαγωγή");
        AddjButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddjButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 799, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(AddjButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DeletejButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(EditjButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(ExitjButton5))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AddjButton1)
                    .addComponent(DeletejButton2)
                    .addComponent(EditjButton3)
                    .addComponent(ExitjButton5))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void DeletejButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeletejButton2ActionPerformed
        if (!General.checkRowSelected(jTable1, "Άλμπουμ", "Άλμπουμ", this)) {
            return;
        }
        this.selectedAlbumClone = this.albumList.get(General.getSelectedRowModelIndex(jTable1));

        ManageAlbumTableJFrame maa;
        try {
            maa = new ManageAlbumTableJFrame(this, null, General.ActionType.Delete);
        } catch (Exception ex) {
            General.showErrorMessage(ex.getMessage(), "Error", this);
            return;
        }
        ApparentModalC.modalSetNextVisible(this, maa);
    }//GEN-LAST:event_DeletejButton2ActionPerformed

    private void EditjButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditjButton3ActionPerformed
        if (!General.checkRowSelected(jTable1, "Άλμπουμ", "Άλμπουμ", this)) {
            return;
        }
        Album a = this.albumList.get(General.getSelectedRowModelIndex(jTable1));

        try {
            //instantiate lazy
            a.getAlbumTitle();
            for (Iterator<Song> iterator = a.getSongList().iterator(); iterator.hasNext();) {
                Song next1 = iterator.next();
            }
            //Περνάμε στην παράμετρο αντίγραφο του managed σ' αυτήν την περίπτωση!!!
            this.selectedAlbumClone = General.getDeepCopy(a);
        } catch (IOException | ClassNotFoundException ex) {
            General.showErrorMessage(ex.getMessage(), "Error", this);
            return;
        }
        ManageAlbumTableJFrame maa;
        try {
            maa = new ManageAlbumTableJFrame(this, a.getSongList(), General.ActionType.Update);
        } catch (Exception ex) {
            General.showErrorMessage(ex.getMessage(), "Error", this);
            return;
        }
        ApparentModalC.modalSetNextVisible(this, maa);
    }//GEN-LAST:event_EditjButton3ActionPerformed

    private void ExitjButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitjButton5ActionPerformed
        dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }//GEN-LAST:event_ExitjButton5ActionPerformed

    private void AddjButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddjButton1ActionPerformed
        this.selectedAlbumClone = new Album();
        this.selectedAlbumClone.setSongList(new ArrayList<>());
        ManageAlbumTableJFrame maa;
        try {
            maa = new ManageAlbumTableJFrame(this, null, General.ActionType.Insert);
        } catch (Exception ex) {
            General.showErrorMessage(ex.getMessage(), "Error", this);
            return;
        }
        ApparentModalC.modalSetNextVisible(this, maa);
    }//GEN-LAST:event_AddjButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AlbumTableJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AlbumTableJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AlbumTableJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AlbumTableJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AlbumTableJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddjButton1;
    private javax.swing.JButton DeletejButton2;
    private javax.swing.JButton EditjButton3;
    private javax.swing.JButton ExitjButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    @Override
    public JTable getTable() {
        return this.jTable1;
    }

    @Override
    public List<Album> getEntityList() {
        return this.albumList;
    }

    @Override
    public EntityManager getEM() {
        return this.RadioStationPUEntityManager;
    }

    @Override
    public Album getSelectedEntityClone() {
        return this.selectedAlbumClone;
    }

    @Override
    public void disableDeleteUpdateIf() {
        General.disableDeleteUpdateIf(jTable1, DeletejButton2, EditjButton3);
    }

    @Override
    public void enableDeleteUpdateIf() {
        General.enableDeleteUpdateIf(jTable1, DeletejButton2, EditjButton3);
    }

    @Override
    public Frame getCaller() {
        return this.caller;
    }

    @Override
    public Frame getNext() {
        return this.next;
    }

    @Override
    public void setCallersNextNull() {
        this.caller.setNext(null);
    }

    @Override
    public void setNext(Frame w) {
        this.next = (JFrame) w;
    }
}
